# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

"""
seller management
add 
delete
modify
...
"""

import utils.pgsql.base.pgconn as pgconn
import time
import json

_tblName = 'tbl_seller'

_DB_SCRIPT = f"""
--  
CREATE TABLE IF NOT EXISTS {_tblName} (
                "sellerId"  SERIAL PRIMARY KEY ,                
                "firmName"   VARCHAR(256) NOT NULL default '',         
                "firmAddress"   VARCHAR(256) NOT NULL default '',        
                "firmAccount" VARCHAR(256) NOT NULL default '',        
                "caseId" INTEGER NOT NULL default 0,    
                "firmPhone" VARCHAR(256) NOT NULL default '',       
                "firmType" VARCHAR(256) NOT NULL default '',        
                "firmCredit"  VARCHAR(256) NOT NULL default '',    
                "charterNumber"  VARCHAR(256)NOT NULL default '',                
                "charterPhotos"   JSON,       
                "charterDate" VARCHAR(256) NOT NULL default '',        
                "organizationCode" VARCHAR(256) NOT NULL default '',       
                "registrationNumber"  VARCHAR(256) NOT NULL default '',     
                "legalName"  VARCHAR(256) NOT NULL default '',               
                "legalPhotos"  JSON,         
                "legalID" VARCHAR(256) NOT NULL default '',        
                "legalPhone" VARCHAR(256) NOT NULL default '',        
                "legalType"  VARCHAR(256) NOT NULL default '身份证',      
                "corporateAccount"  VARCHAR(256) NOT NULL default '' ,               
                "openProve"  VARCHAR(256) NOT NULL default '' ,               
                "bankName"   VARCHAR(256) NOT NULL default '',        
                "branchName" VARCHAR(256) NOT NULL default '',        
                "bankAdress" JSON,        
                "branchNumber" VARCHAR(256) NOT NULL default '',       
                "email"  VARCHAR(256) NOT NULL default '' ,            
                "auditatatus"   VARCHAR(256) NOT NULL default '未审核',    
                "accounttype"  VARCHAR(256) NOT NULL default '',        
                "dealersType" VARCHAR(256) NOT NULL default '身份证',         
                "dealersDate" JSON,         
                "dealersAdress" VARCHAR(256) NOT NULL default '',         
                "dealersProfessional" VARCHAR(256) NOT NULL default '',        
                "bankNumber" VARCHAR(256) NOT NULL default '',         
                "bankbindPhone" VARCHAR(256) NOT NULL default '',         
                "bankbindName" VARCHAR(256) NOT NULL default '',         
                "cardWay" VARCHAR(256) NOT NULL default '后台绑定银行卡',         
                "bankbindType" VARCHAR(256) NOT NULL default '身份证',         
                "bankbindTypeNumber" VARCHAR(256) NOT NULL default '',         
                "bankbindData" VARCHAR(256) NOT NULL default '',         
                "cvv2" VARCHAR(256) NOT NULL default '',        
                "proportion" VARCHAR(32) NOT NULL default '0',   
                "showDate" INTEGER NOT NULL default 0,    
                "showDate1" json,   
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default ''
                );
"""


class PgSeller:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

  
    def addseller(self, dic) -> str:
        dic['createTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        if 'charterPhotos' in dic:
            dic['charterPhotos'] = json.dumps(dic['charterPhotos'])
        if 'legalPhotos' in dic:
            dic['legalPhotos'] = json.dumps(dic['legalPhotos'])
        if 'bankAdress' in dic:
            dic['bankAdress'] = json.dumps(dic['bankAdress'])
        if 'dealersDate' in dic:
            dic['dealersDate'] = json.dumps(dic['dealersDate'])
        if 'equipmentFor' in dic:
            dic['equipmentFor'] = json.dumps(dic['equipmentFor'])
        if 'showDate1' in dic:
            dic['showDate1'] = json.dumps(dic['showDate1'])

        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

        
        sql = f"""insert into {_tblName} ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"sellerId"}" """
        return pgconn.pgMainConn.exec_fetchone(sql)

  
    def modify(self, ids, dic) -> bool:
        dic['updateTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())

        if 'charterPhotos' in dic:
            dic['charterPhotos'] = json.dumps(dic['charterPhotos'])
        if 'legalPhotos' in dic:
            dic['legalPhotos'] = json.dumps(dic['legalPhotos'])
        if 'bankAdress' in dic:
            dic['bankAdress'] = json.dumps(dic['bankAdress'])
        if 'dealersDate' in dic:
            dic['dealersDate'] = json.dumps(dic['dealersDate'])

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"sellerId\" = \'{}\' ".format(ids)
        return self._pgConn.exec(sql)
        

    def allByauditatatus(self, auditatatus) -> list:
        sql = "select * from {} where \"auditatatus\" = \'{}\'".format(
            _tblName, auditatatus)
        return self._pgConn.exec_fetchall(sql)

    def all(self) -> list:
        sql = "select a.*,n.\"caseName\" from {} a left join tbl_case n on a.\"caseId\" = n.\"caseId\" where n.\"dataValid\" !=0 ".format(
            _tblName)
        return self._pgConn.exec_fetchall(sql)

 
    def firmNameget(self, firmName) -> list:
        sql = "select \"firmName\" from {}  where  \"firmName\" = \'{}\' ".format(
            _tblName, firmName)
        return self._pgConn.exec_fetchall(sql)

 
    def accounttypeget(self, sellerId) -> list:
        sql = "select \"accounttype\" from {}  where  \"sellerId\" = \'{}\' ".format(
            _tblName, sellerId)
        return self._pgConn.exec_fetchall(sql)

 
    def firmNameeditget(self, firmName, ids) -> list:
        sql = "select \"firmName\" from {}  where  \"firmName\" = \'{}\' and  \"sellerId\" !=  \'{}\'".format(
            _tblName, firmName, ids)
        return self._pgConn.exec_fetchall(sql)

    def allByoperator(self, operatorId) -> list:
        sql = "select a.*,n.\"caseName\" from {} a left join tbl_case  n on a.\"caseId\" = n.\"caseId\" where a.\"firmAccount\" = \'{}\' and n.\"dataValid\" !=0 ".format(
            _tblName, operatorId)
        return self._pgConn.exec_fetchall(sql)

    def allunusecase(self, operatorId) -> list:
        sql = "select a.\"caseId\",\"caseName\" from tbl_case a left join {}  b on a.\"caseId\"=b.\"caseId\" where b.\"caseId\" is null and a.\"operatorId\" = \'{}\' and a.\"dataValid\" !=0" .format(
            _tblName, operatorId)
        return self._pgConn.exec_fetchall(sql)

    def allunusecasecaseid(self, caseId) -> list:
        sql = "select a.\"caseId\",\"caseName\" from tbl_case a left join {}  b on a.\"caseId\"=b.\"caseId\" where b.\"caseId\" is null and a.\"caseId\" = \'{}\' and a.\"dataValid\" !=0" .format(
            _tblName, caseId)
        return self._pgConn.exec_fetchall(sql)

    def allBycase(self, caseId) -> list:
        sql = "select a.*,n.\"caseName\" from {} a left join tbl_case  n on a.\"caseId\" = n.\"caseId\" where a.\"caseId\" = \'{}\' and n.\"dataValid\" !=0  ".format(
            _tblName, caseId)
        return self._pgConn.exec_fetchall(sql)

    def allSeller(self, operatorId) -> list:
        sql = "select * from {} where \"sellerId\" = \'{}\'".format(
            _tblName, operatorId)
        return self._pgConn.exec_fetchall(sql)

    def delete(self, ids) -> bool:
        sql = "delete from {} where \"sellerId\" = \'{}\' ".format(
            _tblName, ids)
        return self._pgConn.exec(sql)

    def deletefirm(self, ids) -> bool:
        sql = "delete from {} where \"caseId\" = \'{}\' ".format(
            _tblName, ids)
        return self._pgConn.exec(sql)

# pg = PgUser()
# pg.createTbl()
